﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace Inaction.Rule
{
    [Serializable]
    public class EnumDescription
    {
        [DisplayName("键")]
        public int Key
        {
            get
            {
                if (Value == null) return 0;
                return (int)Value;
            }
        }
        [DisplayName("值")]
        public object Value { get; set; }
        [DisplayName("说明")]
        public string Description { get; set; }

        public EnumDescription()
        {
        }

        public EnumDescription(object enumValue)
        {
            var type = enumValue.GetType();
            if (!type.IsEnum)
            {
                throw new Exception(Inaction.Resource.Properties.Resources.NotIsEnumType);
            }
            var field = type.GetField(enumValue.ToString());
            var description = field.GetCustomAttribute<DescriptionAttribute>();
            Description = description == null ? enumValue.ToString() : description.Description;
            Value = enumValue;
        }

        public static string GetDescription(object enumValue)
        {
            if (enumValue == null) return null;
            var type = enumValue.GetType();
            if (!type.IsEnum)
            {
                throw new Exception(Inaction.Resource.Properties.Resources.NotIsEnumType);
            }
            var field = type.GetField(enumValue.ToString());
            var description = field.GetCustomAttribute<DescriptionAttribute>();
            if (description == null)
            {
                return enumValue.ToString();
            }
            return description.Description;
        }
    }
}
